import {Tree, Card, Icon, Tooltip, Tag} from 'antd';
// import Tree from '../../_antd1.11.2/tree';
// import Card from '../../_antd1.11.2/card';
// import Icon from '../../_antd1.11.2/icon';
// import Tooltip from '../../_antd1.11.2/tooltip';
// import Tag from '../../_antd1.11.2/tag';

const TreeNode = Tree.TreeNode;

const random = () => {
    return "_id"+(new Date().getTime()) +"_"+ Math.random()*1000;
}

class WeaTreeEdit extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            datas:[],
            editMap:{},
            //editData:props.editData||{},
            isLoad:false
        }
    }
    componentWillReceiveProps(nextProps) {
        if(nextProps.editData&&this.props.editData&&JSON.stringify(this.props.editData)!==JSON.stringify(nextProps.editData)) {
            let {editMap} = this.state;
            const {keyParam} = this.props.paramField;
            if(nextProps.editData&&nextProps.editData["_"+keyParam]) {
                const keyValue = nextProps.editData["_"+keyParam];
                nextProps.editData.isEdit = editMap[keyValue]&&editMap[keyValue].isEdit;
                editMap[keyValue] =  nextProps.editData;
                // console.log("editData:",nextProps.editData);
                //console.log("eidtMap:",editMap);
                this.setState({
                    //editData:nextProps.editData,
                    eidtMap:editMap
                });
            }
        }
        const {keyParam} = this.props.paramField;
        if(this.props.childrenData[keyParam]!==nextProps.childrenData[keyParam]) {
            let {datas} = this.state;
            this.setData(datas,nextProps.childrenData);
            this.setState({
                datas:datas
            });
        }
        if(!this.state.isLoad&&nextProps.datas&&nextProps.datas.length>0) {
            this.setState({
                isLoad:true,
                datas:nextProps.datas
            })
        }
    }
    setData(datas,obj) {
        let find = false;
        const {keyParam,treeCodeParam} = this.props.paramField;
        for(let i=0;i<datas.length&&!find;i++) {
            let data = datas[i];
            if(data[keyParam]===obj[keyParam]) {
                obj.isLoad = true;
                datas[i] = obj;
                find = true;
            }
            else if(obj[treeCodeParam].indexOf(data[treeCodeParam]+"-")===0&&data.children&&data.children.length>0) {
                this.setData(data.children,obj);
            }
        }
    }
    render() {
        const {datas} = this.state;
        //console.log("datas:",datas);
        return (
            <Tree
                selectedKeys={[]}
                {...this.props}
                loadData={this.loadData.bind(this)}
            >
            {
                datas.map((obj)=>{
                    return this.renderNode(obj);
                })
            }
            </Tree>
        )
    }
    loadData(treeNode) {
        //console.log("treeNode:",treeNode);
        if(typeof this.props.loadData==="function"&&!treeNode.props.data.isLoad) {
            return this.props.loadData(treeNode);
        }
        else {
            return new Promise((resolve) => {
                //console.log("treeNode:",treeNode);
                resolve();
            })
        }
    }
    renderTitle(obj) {
        let {editMap} = this.state;
        const {keyParam} = this.props.paramField;
        const {showCom,editCom,canEdit} = this.props;
        const keyValue = obj["_"+keyParam];
        // if(editData["_"+keyParam]&&editData["_"+keyParam]!==""&&editData["_"+keyParam]===obj["_"+keyParam]) {
        //     obj = {...editData};
        // }
        if(editMap[keyValue]) {
            obj = {...editMap[keyValue]};
        }
        const keyValueReal = obj[keyParam];
        const isEdit = editMap[keyValue] && editMap[keyValue].isEdit;
        //console.log("keyValue:",keyValue," keyValueReal:",keyValueReal);
        //console.log("editMap[keyValue]:",editMap[keyValue]," obj:",obj);
        return (
            <span>
                <span>{isEdit?editCom(obj):showCom(obj)}</span>
                {
                    canEdit && isEdit && (
                        <Tooltip placement="top" title="保存">
                            <Icon type="save" style={{marginLeft: 12}}
                                  onClick={() => {
                                      if(editMap[keyValue][keyParam].indexOf("_")===0) {
                                          if (typeof this.props.onAdd === "function") {
                                              this.props.onAdd(editMap[keyValue]);
                                          }
                                      }
                                      else {
                                          if (typeof this.props.onEdit === "function") {
                                              this.props.onEdit(editMap[keyValue]);
                                          }
                                      }
                                      editMap[keyValue].isEdit = false;
                                      this.setState({
                                          editMap: editMap
                                      });
                                  }}/>
                        </Tooltip>
                    )
                }
                {
                    canEdit && isEdit && (
                        <Tooltip placement="top" title="取消">
                            <Icon type="close" style={{marginLeft: 12}}
                                onClick={() => {
                                    editMap[keyValue].isEdit = false;
                                    this.setState({
                                        editMap: editMap
                                    });
                                }}/>
                        </Tooltip>
                    )
                }
                {
                    canEdit && isEdit && (
                        <Tooltip placement="top" title="删除">
                            <Icon type="close-square" style={{marginLeft:12}}
                                onClick={()=>{
                                    if (typeof this.props.onDel === "function") {
                                        this.props.onDel(editMap[keyValue]);
                                    }
                                }}
                            />
                        </Tooltip>
                    )
                }
                {
                    canEdit && !isEdit && (
                    <Tooltip placement="top" title="编辑">
                        <Icon type="edit" style={{marginLeft: 12}}
                              onClick={() => {
                                  editMap[keyValue] = obj;
                                  obj.isEdit = true;
                                  this.setState({
                                      editMap: editMap
                                  });
                              }}/>
                    </Tooltip>)
                }
                {keyValueReal&&keyValueReal.indexOf("_")!==0 && canEdit && (<Tooltip placement="top" title="添加同级">
                    <Icon type="plus-circle" style={{marginLeft:12}}
                          onClick={() => {
                              this.addTreeNode("same",obj);
                              // if (typeof this.props.onAdd === "function") {
                              //     this.props.onAdd({addType:"same"});
                              // }
                          }}
                    />
                </Tooltip>)}
                {keyValueReal&&keyValueReal.indexOf("_")!==0 && canEdit && (<Tooltip placement="top" title="添加下级">
                    <Icon type="plus" style={{marginLeft:12}}
                          onClick={() => {
                              this.addTreeNode("sub",obj);
                              // if (typeof this.props.onAdd === "function") {
                              //     this.props.onAdd({addType:"sub"});
                              // }
                          }}
                    />
                </Tooltip>)}
                {canEdit && (<span style={{marginLeft:12}}>
                {
                    keyValueReal.indexOf("_")===0 && (
                        <Tag>未保存</Tag>
                    )
                }
                </span>)}
            </span>
        )
    }
    renderNode(obj) {
        const {keyParam} = this.props.paramField;
        if(!obj["_"+keyParam]) {
            obj["_"+keyParam] = obj[keyParam];
        }
        //console.log("this:",this);
        const isLeaf = obj.leaf&&(!obj.children||(obj.children&&obj.children.length===0));
        //console.log("obj:",obj);
        //console.log("obj:",obj," isLeaf:",isLeaf," leaf:",obj.leaf);
        return (
            <TreeNode title={this.renderTitle(obj)} key={obj[keyParam]} isLeaf={isLeaf} data={obj} >
            {
                obj.children&&obj.children.map((chObj)=>{
                    return this.renderNode(chObj);
                })
            }
            </TreeNode>
        )

    }
    addTreeNode(addType,obj) {
        let {datas} = this.state;
        let {editMap} = this.state;
        const {keyParam} = this.props.paramField;
        const keyValue = obj["_"+keyParam];
        // if(editData["_"+keyParam]&&editData["_"+keyParam]!==""&&editData["_"+keyParam]===obj["_"+keyParam]) {
        //     obj = {...editData};
        // }
        // else
        if(editMap[keyValue]) {
            obj = {...editMap[keyValue]};
        }
        //console.log("addTreeNode:",obj," addType:",addType);
        if(addType==="same") {
            this.setTreeNodeByTreeCodeSame(datas, obj);
            this.setState({
                datas:datas
            });
        }
        if(addType==="sub") {
            this.setTreeNodeByTreeCodeSub(datas, obj);
            //console.log("datas:",datas);
            this.setState({
                datas:datas
            });
        }
    }
    setTreeNodeByTreeCodeSame(datas,root) {
        const {editMap} = this.state;
        const {treeCodeParam,parentKeyParam,nameParam,keyParam,parentTypeParam} = this.props.paramField;
        let find = false;
        let obj = {};
        for(let i=0;i<datas.length&&!find;i++) {
            let data = datas[i];
            const keyValue = data["_"+keyParam];
            if(editMap[keyValue]) {
                data = editMap[keyValue];
            }
            const treeCode = root[treeCodeParam];
            if (data[treeCodeParam] === treeCode) {
                find = true;
                obj[parentKeyParam] = data[parentKeyParam];
                obj[parentTypeParam] = data[parentTypeParam];
            }
            else if (treeCode.indexOf(data[treeCodeParam] + "-") === 0 && data.children) {
                console.log("treeCode:",treeCode," data[treeCodeParam]:",data[treeCodeParam]," data.children:",data.children," ?:",treeCode.indexOf(data[treeCodeParam] + "-") === 0);
                this.setTreeNodeByTreeCodeSame(data.children, root);
            }
        }
        if(find) {
            obj[keyParam] = random();
            obj["_"+keyParam] = obj[keyParam];
            obj[nameParam] = "新增节点";
            obj["leaf"] = true;
            datas.push(obj);
        }
    }
    setTreeNodeByTreeCodeSub(datas,root) {
        const {editMap} = this.state;
        const {treeCodeParam,parentKeyParam,nameParam,keyParam,parentTypeParam,typeParam} = this.props.paramField;
        let find = false;
        for(let i=0;i<datas.length&&!find;i++) {
            let data = datas[i];
            const keyValue = data["_"+keyParam];
            if(editMap[keyValue]) {
                data = editMap[keyValue];
            }
            //console.log("data:",data," root:",root);
            const treeCode = root[treeCodeParam];
            //console.log("data[treeCodeParam]:",data[treeCodeParam]," treeCode:",treeCode);
            if (data[treeCodeParam] === treeCode) {
                find = true;
                let obj = {};
                obj[parentKeyParam] = data[keyParam];
                obj[parentTypeParam] = data[typeParam];
                if(!data.children) {
                    data.children = [];
                }
                obj[keyParam] = random();
                obj["_"+keyParam] = obj[keyParam];
                obj[nameParam] = "新增节点";
                obj["leaf"] = true;
                //console.log("data:",data," obj:",obj);
                data.children.push(obj);
                datas[i] = data;
            }
            else if (treeCode.indexOf(data[treeCodeParam] + "-") === 0 && data.children) {
                this.setTreeNodeByTreeCodeSub(data.children, root);
            }
        }

    }
}

export default WeaTreeEdit